﻿#include "pch.h"
#include "ChapterManager.h"
#include "ChapterManager.g.cpp"
#include <regex>
#include <filesystem>
#include <fstream>
#include <string>
#include "Utils.h"

const std::wregex TITLE_REGEX{ LR"(第\s?[\d一二三四五六七八九十百千万]+\s?章)" };
const std::wstring ERROR_MESSAGE_DECODING = L"错误：解码失败。";

namespace winrt::NovelReader::implementation
{
    ChapterManager::ChapterManager(hstring const& filePath)
    {
        m_filePath = filePath;
        m_sqlFilePath = this->GetSqliteFilePath();
        //m_canLoadFromSqlite = std::filesystem::exists(m_sqlFilePath); 
    }

    winrt::NovelReader::ChapterCollection ChapterManager::GetChaptersFromTextFile() const
    {
        auto collection = winrt::NovelReader::ChapterCollection();

        // 读取文件
        std::ifstream file{ m_filePath, std::ios_base::binary };
        std::string bytes{ std::istreambuf_iterator(file), {} };
        file.close();

        // 解码
        int codePage = winrt::NovelReader::Service::GetTextCodePage(bytes);
        if (codePage == -1) {
            collection.Add(ERROR_MESSAGE_DECODING, L"", 0); 
            return collection; 
        }

        auto fileContent = winrt::NovelReader::Service::ToUtf16(bytes, codePage);
        auto allLines = winrt::NovelReader::Service::SplitTextByCRLF(fileContent);
        fileContent.clear(); 

        
        size_t totalLines = allLines.size();
        size_t lineIndex = 0;
        std::wostringstream textStream;

        Chapter currentChapter = winrt::NovelReader::Chapter(this->BookName(), L"", 0);
        collection.Add(currentChapter);

        while (lineIndex < totalLines) {
            auto& lineText = allLines[lineIndex];
            if (!IsTitle(lineText)) {
                textStream << lineText << std::endl;
            }
            else {
                currentChapter.Text(textStream.str());
                currentChapter = winrt::NovelReader::Chapter(lineText, L"", collection.Size());
                collection.Add(currentChapter);
                textStream = std::wostringstream();
            }
            ++lineIndex;
        }
        allLines.clear();
        return collection;
    }

    winrt::Windows::Foundation::IAsyncOperation<winrt::NovelReader::ChapterCollection> ChapterManager::GetChaptersAsync()
    {
        auto ui_thread = winrt::apartment_context();
        co_await winrt::resume_background();
        winrt::NovelReader::ChapterCollection result = this->GetChaptersFromTextFile();
        co_await ui_thread;
        co_return result;
    }

    hstring ChapterManager::BookName() const
    {
        std::filesystem::path path{ m_filePath };
        return hstring{ path.stem().c_str() };
    }

    bool ChapterManager::IsTitle(std::wstring const& line)
    {
        std::wstring input = (line.size() <= 12) ? line : line.substr(0, 12);
        return std::regex_search(input, TITLE_REGEX);
    }

    std::wstring ChapterManager::GetSqliteFilePath() const
    {
        auto cacheFolder = winrt::NovelReader::Service::GetCacheFolder();
        auto bookName = this->BookName();
        auto sqliteFileName = bookName + L".sqlite";

        auto hashName = winrt::NovelReader::Service::SimpleHash(sqliteFileName.c_str()); 
        hashName += L".sqlite";
        auto result = cacheFolder.wstring() + L"\\" + hashName; 
        return result;
    }
}
